﻿using System;
using System.Diagnostics;
using LujHosting.Internal;
using Microsoft.Extensions.DependencyInjection;

namespace LujHosting;

public static class ServiceCollectionExt {

  public static IServiceCollection AddSingletonAuto<S>(this IServiceCollection collection) where S : class {
    HostConfigureExt.ServiceItem[] init = Array.Empty<HostConfigureExt.ServiceItem>();

    RootDependencyCollector depCollect = RootDependencyCollector.New(typeof(S), init);
    ServiceAutoConfig auto = new(depCollect, init);

    auto.Configure(Array.Empty<Type>(), collection);
    return collection;
  }

  public static S BuildService<S>(this IServiceCollection collection) where S : class {
    ServiceProvider provider = collection
      .AddSingletonAuto<S>()
      .BuildServiceProvider();

    S? service = provider.GetService<S>();
    Debug.Assert(service != null);
    return service;
  }
}
